package com.nightpiter.view.drawer.dynamic;

import java.util.ArrayList;

import com.nightpiter.model.objects.Station;
import com.nightpiter.model.objects.Transfer;
import com.nightpiter.model.objects.Tunnel;
import com.nightpiter.view.Calculator;
import com.nightpiter.view.drawer.ClassicMetroDrawer;
import com.nightpiter.view.graphics.Canvas;
import com.nightpiter.view.graphics.Point;
import com.nightpiter.view.graphics.PointF;

/**
 * @author Eldar Abusalimov (eldar.abusalimov@gmail.com)
 */
public class DynamicMetroDrawer extends ClassicMetroDrawer {

	/** a structure to draw */
	private Structure structure;

	/**
	 * default constructor
	 */
	public DynamicMetroDrawer() {
	}

	@Override
	protected boolean internalPrepare() {
		this.structure = new Structure(modelData, mode);
		return super.internalPrepare();
	}

	@Override
	public boolean update(Station station) {
		return false;
	}

	@Override
	protected void internalDrawMetro(Canvas canvas, Calculator calculator) {
		IntermediateAmoeba.setup();
		PrimitiveAmoeba.setup();
		Bacillus.setup();

		for (AmoebaUltimate amoeba : structure.getAmoebas()) {
			amoeba.applyCalculator(calculator);
		}

		for (BacillusUltimate bacillus : structure.getBacilli()) {
			bacillus.draw(canvas, calculator);
		}

		for (AmoebaUltimate amoeba : structure.getAmoebas()) {
			amoeba.draw(canvas);
		}
	}

	@Override
	public void selectStation(Station station, Canvas canvas,
			Calculator calculator) {
		// TODO Auto-generated method stub

	}

	@Override
	public void showWay(ArrayList<Tunnel> selectedTunnels,
			ArrayList<Transfer> selectedTransfers,
			ArrayList<Station> selectedStations, Canvas canvas,
			Calculator calculator) {
		// TODO Auto-generated method stub

	}

	@Override
	public Station[] searchStation(Point point, Calculator calculator) {
		for (AmoebaUltimate amoeba : structure.getAmoebas()) {
			amoeba.applyCalculator(calculator);
		}
		structure.getDrawnAmoebas();

		final int DELTA = 7;
		float minDist = Float.POSITIVE_INFINITY;
		float dist = 0;

		PointF pointF = new PointF();
		Amoeba nearestAmoeba = null;
		for (Amoeba amoeba : structure.getDrawnAmoebas()) {
			pointF = amoeba.pointF;
			dist = pointF.distanceTo(point);
			if (dist < minDist) {
				minDist = dist;
				nearestAmoeba = amoeba;
			}
		}

		if (nearestAmoeba != null && minDist < DELTA) {
			Station[] stations = new Station[nearestAmoeba.stations.length];
			System.arraycopy(nearestAmoeba.stations, 0, stations, 0,
					nearestAmoeba.stations.length);
			return (Station[]) stations;
		}
		return new Station[0];
	}

}
